<?php

class Category_IndexController extends Ac_Controller_Action
{
    private $category;
    public function preDispatch()
    {
        
        $this->_helper->_layout->setLayout('layout');

        if ($this->_request->getActionName() === 'view-all' || $this->_request->getActionName() === 'disclamer'){
                return parent::preDispatch();
        }        
        
        $level3 = $this->_request->getParam('level3');
        $level2 = $this->_request->getParam('level2');
        $level1 = $this->_request->getParam('level1');
        
        $lang = 'tc';

        if ($this->_request->getActionName() !== 'view-all' && $this->_request->getActionName() !== 'disclamer') {
            $level_num = 3;
            if ($level1 !== null)  {
                $level_num = 1;
                $cat1 = Model_Category::one(array('url_sc' => $level1, 'status' => Model_Category::STATUS_ACTIVE, 'path' => array('$size' => ($level_num))));
                $level = $level1;
            }

            if ($level2 !== null)  {
                $level_num = 2;
                //$level = $this->_request->getParam('level2');
                $cat2 = Model_Category::one(array('url_sc' => $level2, 'status' => Model_Category::STATUS_ACTIVE, 'path' => array('$all' => array($cat1->_id), '$size' => $level_num)));
                $level = $level2;
            }

            if ($level3 !== null)  {
                $level_num = 3;
                //$level = $this->_request->getParam('level2');
                //$cat3 = Model_Category::one(array('url_en' => $level3, 'path' => $cat2->_id, 'path' => array('$size' => $level_num)));
                $cat3 = Model_Category::one(array('url_sc' => $level3, 'status' => Model_Category::STATUS_ACTIVE, 'path' => array('$all' => array($cat2->_id), '$size' => $level_num)));
                $level = $level3;
            }

            
            $this->view->level = $level;

            $session = new Zend_Session_Namespace('current_language');
            if (!empty($cat3)) {
                $category = $cat3;
            } elseif (!empty($cat2)) {
                $category = $cat2;
            } elseif (!empty($cat1)) {
                $category = $cat1;
            }
            $redirect = false;
            if (!empty($level1) && empty($cat1)){ //assume old category
                $cat = Model_Category::one(array('url_sc' => $level1, 'sa'=> 1));
                if (!empty($cat)) {
                    $new_cat = Model_Category::find($cat->moved_to);
                    if (!empty($new_cat)) {
                        $redirect = $new_cat;
                        $lang = 'sc';
                    }
                }
            }

            if (!empty($level2) && empty($cat2)){ //assume old category
                $cat = Model_Category::one(array('url_sc' => $level2, 'sa'=> 1));
                if (!empty($cat)) {
                    $new_cat = Model_Category::find($cat->moved_to);
                    if (!empty($new_cat)) {
                        $redirect = $new_cat;
                        $lang = 'sc';
                    }
                }
            }
            if (!empty($level3) && empty($cat3)){ //assume old category
                $cat = Model_Category::one(array('url_sc' => $level3, 'sa'=> 1));
                if (!empty($cat)) {
                    $new_cat = Model_Category::find($cat->moved_to);
                    if (!empty($new_cat)) {
                        $redirect = $new_cat;
                        $lang = 'sc';
                    }
                }
            }

            if (empty($category)) {
                header('Location: /');
                exit;
            }


            if (empty($redirect)) {
                $parent = $category->getParent();
                if (!empty($parent)) {
                    $parent = Model_category::find($parent->_id);
                }
                
                //var_dump($lang, $cat1->nm_en, $cat2->nm_en, $cat3->nm_en, $category->nm_en, (string)$cat2->_id, (string)$parent->nm_en);exit;
                //$category = Model_Category::one(array('url_en' => $level, 'path' => array('$size' => ($level_num))));
                if (empty($category)) {//not english
                    $category = Model_Category::one(array('url_tc' => $level, 'path' => array('$size' => ($level_num))));
    
                    if (!empty($category)) {//not english
                        $this->category = $category;
                        $session->current_language = 'tc';
                        $this->_request->setParam('category', $category);
                    }
                    //let it slide
                } else {
                    $this->category = $category;
                    $session->current_language = $lang;
                    $this->_request->setParam('category', $category);
                }
            }
        }
        
        $this->_setParam('lang', $lang);
        parent::preDispatch();
        if (!empty($redirect)) {
            header('Location: '.$redirect->url(true, $lang));
            exit;
        }
        
    }

    public function populateNewStuff()
    {
       // This is the 'new items horizontal list at the top of the category page//
       $this->view->newstuff =  $this->category->getMostRecentListing(12);
    }
    
    public function populatePopular()
    {
        // This is the 'new items horizontal list at the bottom of the category page//
        if ($this->category->id == 'mc52') { //business directory
            $this->view->popular_company = $this->category->getPopularCompany(12);
        } else {
            $this->view->popular = $this->category->getPopularListing(12);
        }
    }

    public function populateCategoryData()
    {
        if ($this->category == null) {// category not found
            throw new Ac_Exception_MissingCategory();
        }

        //check for disclamer
        $session = new Zend_Session_Namespace('disclamer');
        if (!empty($_GET['disc'])) {
            $session->disclamer = 1;
        } else {
            $top = Model_Category::find($this->category->path[0]);
            if ($top->id == 'mc69' && empty($session->disclamer)) {
                $this->_redirect($this->view->geturl('disclamer', 'category', null, null, array('url' => $this->category->url())));
            }
        }
        
        // pass mongocollection to view to show
        $parents = $this->category->getParentTree();
        $this->view->path = $parents;

        foreach($parents as $parent) {
            if(count($parents) == 1 && !empty($this->category->page_title)) {
                $this->addTitle(CURRENT_CITY_NAME . $this->category->page_title);    
            } else {
                $this->addTitle(CURRENT_CITY_NAME . $this->view->t($parent->name_sc));
            }
        }
        
        
        if ($this->category->getLevel() > 1) {
            $this->setCanonical($this->category->url(false, $this->current_language));
            Zend_Registry::set('category_list_id', (string)$this->category->_id);
            return $this->_forward('regular', 'index', 'search');
        }


        //facet search
        $solr = Ac_Search::getClient();
        $additionalParameters = array();
        $additionalParameters['fq'] = ' +status:1 +category_l1:' . $this->category->_id;
        $additionalParameters['facet'] = 'true';
        $additionalParameters['facet.mincount'] = '1';
        $additionalParameters['facet.limit'] = '10';
        $additionalParameters['facet.field'] = array(
            'category_l2',
            'make',
            'bedroom',
            'area_l2',
            'area_l1',
        );

        $tmp = $this->category->price_range;
        $keys = array('price' => $tmp);
        $force_facet_field = array();

        $_GET['small_category_list']   =(string)$this->category->_id;

        if ($this->category->customization == 'job') {
            $additionalParameters['facet.field'][] = 'salary';
            $additionalParameters['facet.field'][] = 'salary_hour';
            $_GET['small_category_list'] = (string)$this->category->_id;
        }
        
        if ($this->category instanceof Model_Category_CarMotorcycleBoat) {
            //$this->view->disabled_facet = array('category_l2');
            $_GET['small_category_list'] = (string)$this->category->_id;
            $_GET['category_attached']   = CAR_CATEGORY;
            $cat = Model_Category::find(CAR_CATEGORY);
            $keys = array('price' => $cat->price_range); 
            $additionalParameters['fq']  = ' +status:1 +category_l2:' . CAR_CATEGORY;

            //add second level category
            foreach($this->category->getChildren() as $child) {
                //$car = Model_Listing::find(CAR_CATEGORY);
                if (!empty($child->listing_count)) {
                    $force_facet_field['category_l2'][(string)$child->_id] = (int)$child->listing_count;
                }
            }
            arsort($force_facet_field['category_l2'], SORT_NUMERIC);
        }

        if ($this->category->id == 'mc52') {
            $keys = array();
        }

        if ($this->category instanceof Model_Category_Property) {
            $keys = array();
            $_GET['small_category_list'] = (string)$this->category->_id;
            //$cat = Model_Category::find(RESIDENTIAL_FOR_RENT);
            $price_range_rent = $this->category->price_range_rent;
            $keys['rent_price'] = $price_range_rent;

            $cat = Model_Category::find(RESIDENTIAL_FOR_SALE);
            $price_range_sale = $this->category->price_range_sale;
            $keys['sale_price'] = $price_range_sale;
        }
/*
        if ($this->category->customization == 'job') {
        } elseif($this->category->customization == 'residential' || $this->category->customization == 'commercial') {
            $id = (string)$this->category->_id;
            $keys = array();
            if ($id == RESIDENTIAL_FOR_RENT || $id == COMMERCIAL_FOR_RENT) {
                $keys = array('rent_price' => $cat->price_range_rent);
            } elseif($id == RESIDENTIAL_FOR_SALE || $id == COMMERCIAL_FOR_SALE) {
                $cat = Model_Category::find($main_cat);
                $keys = array('sale_price' => $cat->price_range_sale);
                $_GET['view'] = empty($_GET['view']) ? 'list' : $_GET['view'];
            }
        } elseif($this->category instanceof Model_Category_Property) {
            $this->view->disable_price = true;
        } elseif(in_array($this->category->customization, array('car', 'motorcycle','boat'))) {
            $this->view->disable_price = true;
        }
*/
/*
        $tmp = $this->category->price_range;
        $additionalParameters['facet.query'] = array();
        foreach ($tmp as $k => $v) {
            $v['min'] = empty($v['min']) ? '*' : $v['min'];
            $v['max'] = empty($v['max']) ? '*' : $v['max'];
            $additionalParameters['facet.query'][] = 'price:['.$v['min'].' TO '.$v['max'].']';
        }
*/

        $additionalParameters['facet.query'] = array();
        foreach($keys as $key => $tmp) {
            if (!empty($tmp)) {
                foreach ($tmp as $k => $v) {
                    $v['min'] = empty($v['min']) ? '*' : $v['min'];
                    $v['max'] = empty($v['max']) ? '*' : $v['max'];
                    $additionalParameters['facet.query'][] = $key . ':['.$v['min'].' TO '.$v['max'].']';
                }
            }
        }

        $query = '*:*';
        $list  = $solr->search($query, 0, 0, $additionalParameters);

        $facet_queries = array();
        foreach($list->facet_counts->facet_queries as $name => $num){
            $arr = array();
            $tmp  = explode(':', $name);
            $name = $tmp[0];
            if (!empty($facet_queries[$name])) {
                $arr = $facet_queries[$name];
            }
            $arr[] = array('range' => $tmp[1], 'count' => $num);
            $facet_queries[$name] = $arr;
        }

        if ($this->category instanceof Model_Category_CarMotorcycleBoat) {
            //unset($_GET['category_attached']);
        }

        foreach($force_facet_field as $k => $field) {
            $list->facet_counts->facet_fields->$k = $field;
        }

        $this->view->facet_counts  = $list->facet_counts;

        $this->view->facet_queries = $facet_queries;
        
         if (DISPLAY_DEBUG) {
            echo '<pre style="clear:both">';
            var_dump($_GET);
            var_dump($additionalParameters);
            if (!empty($additionalParameters['qf'])) {
                print_r($additionalParameters['qf']);
            }
            echo '</pre>';
        }
        
        if (!empty($this->category->description)) { 
            $this->view->headMeta()->appendName('description', substr($this->category->description, 0, 160));
        }    
        
        //$list = $solr->search('+level: '.($category->getLevel()+1).' +type_obj:'.Model_Category::TYPE.' +category:'.(string)$category->_id, 0, 100, array());
        $critearia = array('display_website' => 1, 'status' => Model_Category::STATUS_ACTIVE, 'path.' . ($this->category->getLevel() - 1) => $this->category->_id, 'path' => array('$size' => ($this->category->getLevel() + 1)));
        $category  = $this->category;
        $this->view->category_list = $category::all($critearia)->sort(array('pos'=>1));
        $this->view->category = $this->category;
        //echo "<PRE>";print_r($this->view->category);exit;
    }

    public function populateCarousel()
    {
             // NOW do the favourites carousel
            //TODO: find the last level of the category if limited per category
            //$it = Model_Listing::all(array('fv' => true))->limit(15);
           /* $it = $this->category->getPopularListing(15);
            $AllpicklistArray = array();
            if($it->count()){
                foreach($it as $ele) {
                    $AllpicklistArray[] = $ele;
                }
            }
            
            if (empty($AllpicklistArray)) {
                $this->view->picklist = array();
                return;
            }
            //$AllpicklistArray  = array_pad($AllpicklistArray ,5,''); // make the array at least 5 items; put in blanks as filler
            if (count($AllpicklistArray) < 5) {
                $picklist = range(0,count($AllpicklistArray)-1);
            }
            else {
                $picklist = array_rand($AllpicklistArray, min(count($AllpicklistArray), 5) ); // 5 picked randomly
            }
           
            $list = array();
            foreach($picklist as $k) {
                $list[] = $AllpicklistArray[$k];
            }*/
            
        $hp   = Model_Todayspick::getCategory($this->category->_id);
        $arr  = array();
	    $list = array();
        if(!empty($hp)){	
	        foreach($hp as $k => $ls){
	        	if(!empty($ls->listing_id)){
		        	foreach($ls->listing_id as $lsid){
		        		if(empty($lsid)){
							continue;
						}
						$arr[] = $lsid;
					}
				}	
			}
	        if(!empty($arr)){
		        shuffle($arr);
		        $arr = array_slice($arr, 0, 5);
		        //$res = Model_Listing::all(array('_id' => array('$in' => $arr)));
		        foreach($arr as $val) {
		            $tmp =  Model_Listing::find(new MongoId($val));
		            if (!empty($tmp)) {
		                $list[] = $tmp;
		            }
		        }
			}
		}
		//echo count($list). " ".(string)$this->category->_id;
        $this->view->picklist = $list;


    }
    public function indexAction()
    {
        
        $this->populateCategoryData();
        $this->populateCarousel();
        $this->populateNewStuff();
        $this->populatePopular();
        
        $subcat = $this->category->getChildren();
        $tmp    = array();
        foreach($subcat as $cat) {
            $tmp[] = $cat->_id;
        }
        //$tmp   = Model_Listing::all(array('ca' => array('$in' => $tmp), 'sa' => 1));
        $tmp   = Model_Listing::distinct('us', array('ca' => array('$in' => $tmp), 'sa' => 1));
        shuffle($tmp);
        $users = array();
        //foreach($tmp->skip(rand(0,100)) as $item) {
        foreach($tmp as $item) {
            $user = Model_User::find($item);
            if(!empty($user->cid)){
				//if(empty($user->company->image)) {continue;}
			}else{
				//if(empty($user->pp)) {continue;}
			}
			$users[] = $user;
            if(count($users) > 10) {break;}
        }
        $this->view->random_users = $users; 
        
        Zend_Registry::set('main_category', $this->category);
    }

    public function viewAllAction()
    {
        $list = Model_Category::getLevel1(array('status' => Model_Category::STATUS_ACTIVE));
        $this->view->list = $list;
    }

    public function disclamerAction()
    {
        $this->view->url = $_GET['url'];
    }
}
